﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player1Controller : MonoBehaviour {

    public float speed = 1.0f; // 角色移动速度
    public float speedToBall = 1;   //碰撞时给球施加的速度
    public float maxz = -2;  //控制器可以活动的范围
    public float minz = -4;  //控制器可以活动的范围

    private Vector3 target; // 目标位置
    private bool isOver = true; // 移动是否结束
    private Rigidbody rb;

    private void Start() {
        rb = GetComponent<Rigidbody>();
    }

    void Update() {
        if (Input.GetMouseButton(0)) {
            GetMonsePos();
        }
        MoveTo(target);
    }

    // 1 获取鼠标点击的位置
    public void GetMonsePos() {
        // a 创建射线
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);// 从摄像机发射出一条经过鼠标当前位置的射线
        // b 发射射线
        RaycastHit hitInfo = new RaycastHit();
        if (Physics.Raycast(ray, out hitInfo)) {
            // 获取碰撞点位置
            if (hitInfo.collider.name == "up" && hitInfo.point.z > minz && hitInfo.point.z < maxz) {
                target = hitInfo.point;
                target.y = 1.12f;// 地面的y坐标为0，而cube的y必须为0.5f才能看得见
                isOver = false;
            }
        }
    }

    // 2 让角色移动到目标位置
    public void MoveTo(Vector3 tar) {
        if (!isOver) {
            Vector3 v1 = tar - transform.position;
            rb.velocity = v1.normalized * speed;
            //transform.position += v1.normalized * speed * Time.deltaTime;
            // 到达目标位置
            if (Vector3.Distance(tar, transform.position) <= 0.2f) {
                isOver = true;
                transform.position = tar;
                rb.velocity = new Vector3(0, 0, 0);
            }
        }
    }

    private void OnCollisionEnter(Collision collision) {
        if(collision.gameObject.CompareTag("ball")) {
            Rigidbody collisionRb = collision.gameObject.GetComponent<Rigidbody>();
            Vector3 v1 = rb.velocity.normalized * speedToBall;   //控制器的速度
            Vector3 v2 = collisionRb.velocity;  //球的速度
            Vector3 vertical = collision.transform.position - transform.position;   //球和控制器接触的方向
            Vector3 horizontal = new Vector3(vertical.z, 0, -vertical.x);
            float vVertical = Mathf.Sqrt(v1.sqrMagnitude) * Mathf.Cos(Vector3.Angle(v1, vertical) * Mathf.Deg2Rad) -
                              Mathf.Sqrt(v2.sqrMagnitude) * Mathf.Cos(Vector3.Angle(v2, vertical) * Mathf.Deg2Rad); //球在接触方向的最终速度
            float vHorizontal = Mathf.Sqrt(v2.sqrMagnitude) * Mathf.Sin(Vector3.Angle(v2, vertical) * Mathf.Deg2Rad);   //球在与接触方向垂直的方向上的最终速度
            Vector3 ballv = vVertical * vertical.normalized + vHorizontal * horizontal.normalized;    //球的最终速度
            collisionRb.velocity = ballv;
        }
    }
}
